﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Linq.Dynamic;
using System.Web.Mvc;
using ChoViet.Model;
using ChoViet.Lib.Common;
using ChoViet.Admin.Properties;
using ChoViet.Admin.ViewModels;
using ChoViet.Lib.Paging;
using System.Web.UI.WebControls;
using System.IO;
using System.Data.Linq;
using ChoViet.Lib.Helpers;
using ChoViet.Systems;
using ChoViet.Lib.Mail;

namespace ChoViet.Admin.Controllers
{
    /// <summary>
    /// Author: Takamaru Nguyen
    /// Date: 12/08/2011
    /// </summary>
    [RoleHelper(Roles = RoleSystem.Mail)]
    public class MailController : Controller
    {
        ChoVietDataContext eDataContext = new ChoVietDataContext();

        //
        // GET: /Mail/Create
        public ActionResult Index(int? page)
        {
            try
            {

                if (!page.HasValue)
                    page = 1;
                string order = UserState.getUserStateFromRequest("mail.order", "order", "ID").ToString();
                string orderDir = UserState.getUserStateFromRequest("mail.orderDir", "orderDir", "desc").ToString();
                string keyword = UserState.getUserStateFromRequest("mail.Keyword", "Keyword", "").ToString();
                int catid = Utils.ParseInt(UserState.getUserStateFromRequest("mail.ddlCategory", "ddlCategory", "0").ToString(), 0);

                int pageSize = int.Parse(UserState.getUserStateFromRequest("mail.pageSize", "PageSize", 20).ToString());


                var arr = catid > 0 ? MailManager.GetChild(catid) : new List<int>();

                IPagedList<Mail> mails = eDataContext.Mails
                    .Where(e => catid > 0 ? e.MailCategoryMaps.Where(k => k.CatID == catid).ToList().Count > 0 : true)
                    .Where(e => (string.IsNullOrEmpty(keyword) ? true : e.Subject.ToLower().Contains(keyword.ToLower().Trim())))
                    .OrderBy(string.Format("{0} {1}", order, orderDir))
                    .ToPagedList(page.Value - 1, pageSize);

                MailIndexViewModels m = new MailIndexViewModels();
                m.Categories = MailManager.GetListCategory();
                m.CategoryID = catid;
                m.Keyword = keyword;
                m.Mails = mails;
                ViewData["orderDir"] = orderDir;
                ViewData["order"] = order;

                return View(m);

            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        public ActionResult Create()
        {
            try
            {
                Mail m = new Mail();
                List<MailCategory> mCat = MailManager.GetListCategory();

                return View(new MailInputModels
                {
                    Mail = m,
                    Categories = mCat
                });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Mail/Create

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Create(MailInputModels m)
        {
            try
            {
                UpdateModel(m);
                m.Mail.AddBy = UserManager.GetUserId();
                m.Mail.AddDate = DateTime.Now;
                eDataContext.Mails.InsertOnSubmit(m.Mail);
                eDataContext.SubmitChanges();
                foreach (var item in m.CatID)
                {
                    var map = new MailCategoryMap();
                    map.MailID = m.Mail.ID;
                    map.CatID = item;
                    eDataContext.MailCategoryMaps.InsertOnSubmit(map);                    
                }
                eDataContext.SubmitChanges();
                var sendYN = Request["hdStatus"] != null && Utils.ParseInt(Request["hdStatus"]) > 0 ? true : false;
                if (sendYN) {
                    var members = eDataContext.MailMembers
                        .Where(e => m.CatID.Contains(e.CatID))
                        .Select(e => e.Email)
                        .Distinct()
                        .ToList();
                    List<MailServer> listMailFrom = eDataContext.MailServers.Where(ms => ms.PubYN == true).ToList();
                    int count = listMailFrom.Count();
                    int index = 0;
                    int page = 0;
                    foreach (string to in members)
                    {
                        if (page > 20)
                        {
                            page = 0;
                            index = index++;
                            if (index >= count)
                                index = 0;
                        }
                        SmtpMailer.sendMail(to, listMailFrom[index].Email,listMailFrom[index].Password, m.Mail.Subject, m.Mail.Message, listMailFrom[index].Port, listMailFrom[index].Host);
                        page++;
                    }

                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        public ActionResult Edit(int id)
        {
            try
            {
                var m = eDataContext.Mails.Where(e => e.ID == id).SingleOrDefault();
                List<MailCategory> mCat = MailManager.GetListCategory();
                return View(
                    new MailInputModels
                    {
                        Mail = m,
                        Categories = mCat
                    });
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Menu/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        public ActionResult Edit(int id, MailInputModels m)
        {
            try
            {
                m.Mail = eDataContext.Mails.Where(e => e.ID == id).SingleOrDefault();
                UpdateModel(m);
                m.Mail.ModBy = UserManager.GetUserId();
                m.Mail.ModDate = DateTime.Now;
                eDataContext.SubmitChanges();
                eDataContext.MailCategoryMaps.DeleteAllOnSubmit(eDataContext.MailCategoryMaps.Where(e => e.MailID == id).ToList());
                eDataContext.SubmitChanges();
                foreach (var item in m.CatID)
                {
                    var map = new MailCategoryMap();
                    map.MailID = m.Mail.ID;
                    map.CatID = item;
                    eDataContext.MailCategoryMaps.InsertOnSubmit(map);
                }
                eDataContext.SubmitChanges();
                var sendYN = Request["hdStatus"] != null && Utils.ParseInt(Request["hdStatus"]) > 0 ? true : false;
                if (sendYN)
                {
                    var members = eDataContext.MailMembers
                        .Where(e => m.CatID.Contains(e.CatID))
                        .Select(e => e.Email)
                        .Distinct()
                        .ToList();
                    List<MailServer> listMailFrom = eDataContext.MailServers.Where(ms => ms.PubYN == true).ToList();
                    int count = listMailFrom.Count();
                    int index = 0;
                    int page = 0;
                    foreach (string to in members)
                    {
                        if (page > 20)
                        {
                            page = 0;
                            index = index++;
                            if (index >= count)
                                index = 0;
                        }
                        SmtpMailer.sendMail(to, listMailFrom[index].Email, listMailFrom[index].Password, m.Mail.Subject, m.Mail.Message, listMailFrom[index].Port, listMailFrom[index].Host);
                        page++;
                    }

                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
        //
        // GET: /Menu/Delete/5
        public ActionResult Delete(int id)
        {
            try
            {
                var item = eDataContext.Mails.SingleOrDefault(e => e.ID == id);
                return View(item);
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }

        //
        // POST: /Menu/Delete/5

        [HttpPost]
        public ActionResult Delete(int id, FormCollection collection)
        {
            try
            {
                var item = eDataContext.Mails.SingleOrDefault(e => e.ID == id);
                if (item != null)
                {
                    eDataContext.MailCategoryMaps.DeleteAllOnSubmit(from m in eDataContext.MailCategoryMaps where m.MailID == id select m);
                    eDataContext.Mails.DeleteOnSubmit(item);
                    eDataContext.SubmitChanges();
                }
                return RedirectToAction("Index");
            }
            catch (Exception exp)
            {
                ViewData[Messages.MessageInfo] = exp.Message;
                return View();
            }
        }
    }
}
